package com.example.manage_dzensaas.filter;

import com.example.manage_dzensaas.core.enums.ErrorCodeEnum;
import com.example.manage_dzensaas.core.enums.ReqCodeEnum;
import com.example.manage_dzensaas.core.utils.DateUtils;
import com.example.manage_dzensaas.filter.exception.CustomException;
import com.example.manage_dzensaas.filter.exception.RootPathException;
import com.example.manage_dzensaas.pojo.result.ApiResult;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.validation.ValidatorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

@Component(index = 0)
public class AppFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(AppFilter.class);

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        } catch (CustomException e) {
            ctx.status(e.getCode());
            //LOGGER.error("业务异常: {}", e.getMessage(), e);
            ctx.render(ApiResult.error(ErrorCodeEnum.CUSTOM_EXCEPTION.getCode(), e.getMessage()));
        } catch (RootPathException e) {
            ctx.status(e.getCode());
            //log.error("路径异常: {}", e.getMessage());
            ctx.render(ApiResult.error(ReqCodeEnum.PATH_ERROR.getCode(), e.getMessage()));
        } catch (ValidatorException e) {
            // v1.10.4 后，添加 getCode() 接口
            ctx.status(e.getCode());
            ctx.render(ApiResult.error(ReqCodeEnum.PARAM_ERROR.getCode(), e.getMessage()));
        }  catch (Exception e) {
            ctx.status(500);
            String date = DateUtils.dateToString(new Date(), DateUtils.DATETIME);
            LOGGER.error("{} - 异常: {}", date, e.getMessage(), e);
            ctx.render(ApiResult.error(ErrorCodeEnum.INTERNAL_ERROR.getCode(), date + " - 服务异常"));
        }
    }
}
